import numpy as np
import matplotlib.pyplot as plt
from sklearn.svm import SVC
from sklearn.model_selection import train_test_split

# 1.	完成数据集的加载和初始化（8分）
data = np.loadtxt('bread.txt', delimiter=',')
m = len(data)
x = data[:, :-1]
y = data[:, -1]

# 2.	将数据集洗牌(6分)，合理分割成训练集和测试集(6分)
np.random.seed(1)
a = np.random.permutation(m)
x = x[a]
y = y[a]
x_train, x_test, y_train, y_test = train_test_split(x, y, train_size=0.7)

# 3.	正确调用SVM库函数并训练模型(30分)
clf = SVC(C=10, gamma=20)
clf.fit(x_train, y_train)

# 4.	分别求出训练集和测试集的准确率(20分)
print(f'训练集的准确率: {clf.score(x_train, y_train)}')
print(f'测试集的准确率: {clf.score(x_test, y_test)}')

# 5.	画出整个样本数据并画出分界线(30分)
plt.scatter(x[:, 0], x[:, 1], c=y)
xx, yy = np.mgrid[x[:, 0].min():x[:, 0].max():200j, x[:, 1].min():x[:, 1].max():200j]
zz = clf.predict(np.c_[xx.ravel(), yy.ravel()]).reshape(xx.shape)
plt.contour(xx, yy, zz)
plt.show()
